<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="4">
          <el-button type="primary" @click="openAddDialog">添加分类</el-button>
        </el-col>
      </el-row>
      <el-table
        :data="goodsType"
        style="width: 100%;margin-bottom: 20px;"
        row-key="cat_id"
        border
        :tree-props="{children: 'children'}">
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="cat_name" label="分类名称"></el-table-column>
        <el-table-column prop="cat_deleted" label="是否有效">
          <template slot-scope="scoped">
            <el-button v-if="scoped.row.cat_deteled" type="danger" icon="el-icon-close" circle size="mini"></el-button>
            <el-button v-else type="success" icon="el-icon-check" circle size="mini"></el-button>
          </template>
        </el-table-column>
        <el-table-column prop="cat_level" label="排序">
          <template slot-scope="scoped">
<!--            {{ scoped.row.cat_level == 0 }}-->
            <div v-if="scoped.row.cat_level == 0">
              <el-tag size="mini">一级</el-tag>
            </div>
            <div v-if="scoped.row.cat_level == 1">
              <el-tag type="warning" size="mini">二级</el-tag>
            </div>
            <div v-if="scoped.row.cat_level == 2">
              <el-tag type="success" size="mini">三级</el-tag>
            </div>
<!--            <el-tag v-else-if="scoped.row.cat_leval == 1" size="mini">二级</el-tag>
            <el-tag v-else-if="scoped.row.cat_leval == 2" size="mini">三级</el-tag>-->
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scoped">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="openUpdate(scoped.row.cat_id)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteRoles(scoped.row.cat_id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageInfo.pagenum"
        :page-size="pageInfo.pagesize"
        :page-sizes="[5, 10, 15, 20]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加分类弹窗 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addDialogVisible"
      width="30%" @close="addDialogClosed">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="80px" >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类" prop="cat_pid">
          <el-cascader
            v-model="value"
            :options="allGoodsType"
            :props="{ expandTrigger: 'hover',
                      value: 'cat_id',
                      label: 'cat_name',
                      checkStrictly: true}"
            @change="handleChange">
          </el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveGoodsType">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改分类弹窗 -->
    <el-dialog
      title="修改分类"
      :visible.sync="editDialogVisible"
      width="30%" @close="editDialogClosed">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="80px" >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <el-select v-model="editForm.value" disabled>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editGoodsType">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Categories',
  data () {
    return {
      goodsType: [],
      allGoodsType: [],
      pageInfo: {
        pagenum: 1,
        pagesize: 10
      },
      total: 0,
      addDialogVisible: false,
      editDialogVisible: false,
      addForm: {
        cat_pid: '',
        cat_name: ''
      },
      editForm: {
        id: '',
        cat_name: '',
        value: ''
      },
      addCateObj: {
        cat_pid: 0,
        cat_name: '',
        cat_level: 0
      },
      addFormRules: {
        cat_name: [
          { required: true, message: '请填写分类名称', trigger: 'blur' },
          { min: 2, max: 10, message: '请输入2至10个字符', trigger: 'blur' }
        ]
      },
      editFormRules: {
        cat_name: [
          { required: true, message: '请填写分类名称', trigger: 'blur' }
        ]
      },
      value: ''
    }
  },
  methods: {
    async getGoodsPageType () {
      const { data: res } = await this.$http.get('categories', { params: this.pageInfo })
      if (res.meta.status !== 200) return this.$message.error('加载商品分类数据失败!')
      this.total = res.data.total
      this.goodsType = res.data.result
    },
    async getAllGoodsType () {
      const { data: res } = await this.$http.get('categories', { params: { type: [1, 2] } })
      if (res.meta.status !== 200) return this.$message.error('加载商品分类数据失败!')
      this.allGoodsType = res.data
    },
    handleSizeChange (newSize) {
      this.pageInfo.pagesize = newSize
      this.getGoodsPageType()
    },
    handleCurrentChange (newPage) {
      this.pageInfo.pagenum = newPage
      this.getGoodsPageType()
    },
    // 打开添加分类弹窗
    openAddDialog () {
      // 加载所有分类数据
      this.getAllGoodsType()
      this.addDialogVisible = true
    },
    // 关闭添加分类弹窗
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
      this.value = ''
    },
    // 保存商品分类
    saveGoodsType () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请输入商品名称')
        // 判断分类层级
        if (this.value === '') {
          // 一级
          this.addCateObj.cat_pid = 0
          this.addCateObj.cat_level = 0
        } else if (this.value.length === 1) {
          // 二级
          this.addCateObj.cat_pid = this.value[0]
          this.addCateObj.cat_level = 1
        } else if (this.value.length === 2) {
          // 三级
          this.addCateObj.cat_pid = this.value[1]
          this.addCateObj.cat_level = 2
        }
        this.addCateObj.cat_name = this.addForm.cat_name
        // 调用接口
        const { data: res } = await this.$http.post('categories', this.addCateObj)
        if (res.meta.status !== 201) return this.$message.error('添加商品分类失败!')
        this.$message.success('添加商品分成功!')
        this.addDialogVisible = false
        await this.getGoodsPageType()
      })
    },
    handleChange () {},
    // 打开修改弹窗
    async openUpdate (id) {
      // 通过id查询数据
      const { data: res } = await this.$http.get('categories/' + id)
      if (res.meta.status !== 200) return this.$message.error('加载子级数据失败!')
      this.editForm = res.data
      // 根据父级编号查询父级名称并赋值
      console.log(res.data)
      const { data: parRes } = await this.$http.get('categories/' + res.data.cat_pid)
      if (parRes.meta.status !== 200) {
        this.editForm.value = '根级目录'
      } else {
        this.editForm.value = parRes.data.cat_name
      }
      this.editDialogVisible = true
    },
    // 关闭修改弹窗
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    // 保存修改分类弹窗
    async editGoodsType () {
      // 调用接口修改分类
      const { data: res } = await this.$http.put(
        'categories/' + this.editForm.cat_id, { cat_name: this.editForm.cat_name })
      if (res.meta.status !== 200) return this.$message.error('修改分类失败!')
      this.$message.success('修改分类成功!')
      this.editDialogVisible = false
      await this.getGoodsPageType()
    },
    deleteRoles (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete('categories/' + id)
        if (res.meta.status === 200) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          // 刷新列表
          await this.getGoodsPageType()
        } else {
          this.$message({
            type: 'error',
            message: '删除失败!'
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  },
  created () {
    // 根据分页查询数据
    this.getGoodsPageType()
  }
}
</script>

<style scoped>

</style>
